package com.ruoyi.framework.web.service;

import com.ruoyi.common.core.domain.entity.Users;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.service.IUsersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class AppLoginService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private IUsersService usersService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        Users user = usersService.selectAppUserByUserName(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        if (!Objects.equals(password, user.getUserPwd())) {
            throw new ServiceException("密码不正确");
        }
        LoginAppUser loginAppUser = new LoginAppUser(user.getUserId(), user);
        recordLoginInfo(loginAppUser.getUserId());
        // 生成token
        return appTokenService.createAppToken(loginAppUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(Long userId) {
        Users user = new Users();
        user.setUserId(userId);
    }
}
